<!--
 * @Date: 2021-12-14 10:30:10
 * @LastEditors: LeeKing
 * @LastEditTime: 2021-12-16 19:46:49
 * @FilePath: \admin\src\views\management\users\index.vue
-->
<template>
  <div class="Users">
    <!-- 面包屑 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <!-- 表格 -->
    <div class="card_body">
      <div class="form">
        <div class="Search_input">
          <el-input v-model="input" placeholder="请输入内容">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="selectUser"
            />
          </el-input>
          <el-button
            type="primary"
            class="btn_add"
            @click="dialogFormVisible = true"
          >添加用户</el-button>
        </div>

        <el-table :data="tableData" border style="width: 100%" stripe>
          <el-table-column label="#" width="48" type="index" />
          <el-table-column prop="username" label="姓名" width="277" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="mobile" label="电话" width="277" />
          <el-table-column prop="role_name" label="角色" width="277" />
          <el-table-column label="状态">
            <template
              scope="scope"
            ><el-switch
              v-model="scope.row.mg_state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              @change="ChangeState(scope.row)"
            /></template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="PutUser(scope.row)"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="DelUser(scope.row)"
              />
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="RolesUser(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加 用户表格 -->
      <div class="AddForm">
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
          <el-form
            ref="numberValidateForm"
            :model="numberValidateForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item
              label="用户名"
              prop="username"
              :rules="[{ required: true, message: '请输入用户名,不能为空' }]"
            >
              <el-input
                v-model.number="numberValidateForm.username"
                type="username"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="密码"
              prop="password"
              :rules="[{ required: true, message: '请输入密码,不能为空' }]"
            >
              <el-input
                v-model.number="numberValidateForm.password"
                type="password"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="邮箱"
              prop="email"
              :rules="[
                { required: true, message: '请输入邮箱,不能为空' },
                {
                  pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                  message: '邮箱不合法',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model.number="numberValidateForm.email"
                type="email"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="mobile"
              :rules="[
                { required: true, message: '请输入手机号,不能为空' },
                {
                  pattern:
                    /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                  message: '手机号不合法',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model.number="numberValidateForm.mobile"
                type="mobile"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item class="BtnFormItem">
              <el-button
                type="primary"
                @click="submitForm('numberValidateForm')"
              >提交</el-button>
              <el-button @click="dialogFormVisible = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 修改用户 -->
      <div class="EditUser">
        <el-dialog title="修改用户" :visible.sync="EditDialog">
          <el-form
            ref="EditDialogForm"
            :model="EditDialogForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model.number="EditDialogForm.username"
                type="username"
                autocomplete="off"
                :disabled="true"
              />
            </el-form-item>

            <el-form-item
              label="邮箱"
              prop="email"
              :rules="[
                { required: true, message: '请输入邮箱,不能为空' },
                {
                  pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                  message: '邮箱不合法',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model.number="EditDialogForm.email"
                type="email"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="mobile"
              :rules="[
                { required: true, message: '请输入手机号,不能为空' },
                {
                  pattern:
                    /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                  message: '手机号不合法',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model.number="EditDialogForm.mobile"
                type="mobile"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item class="BtnFormItem">
              <el-button
                type="primary"
                @click="submitEdit('EditDialogForm')"
              >提交</el-button>
              <el-button @click="EditDialog = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          :current-page="CurrentPage"
          :page-sizes="[2, 4, 8, 10]"
          :page-size="PageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 分配用户角色 -->
      <div class="roles">
        <el-dialog title="提示" :visible.sync="RolesDialog" width="50%">
          <div class="roles-box">
            <div>当前用户是:{{ this.roles.username }}</div>
            <div>当前的角色: {{ this.roles.role_name }}</div>
            <span>分配新角色:</span>
            <el-select v-model="select" placeholder="请选择" @focus="onselect">
              <el-option
                v-for="item in rolesList"
                :key="item.value"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="RolesDialog = false">取 消</el-button>
            <el-button type="primary" @click="onRoleSave">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getInfoList,
  addUserInfo,
  PutUserState,
  EditUserInfo,
  DeleteUser,
  putUserRole
} from '@/api/user.js'
import { RolesList } from '@/api/role.js'

export default {
  name: 'Users',

  data() {
    // 添加用户信息

    return {
      tableData: [],
      input: '',
      stateBtn: true,
      // 当前页
      CurrentPage: 1,
      // 每页条数
      PageSize: 2,

      // 总条数
      total: null,
      // 更改后的条数
      ChangeSize: null,

      // 添加用户弹框
      dialogFormVisible: false,
      numberValidateForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户
      EditDialog: false,
      EditUser: {},
      EditDialogForm: {
        username: '',
        email: '',
        mobile: ''
      },

      // 分配角色
      RolesDialog: false,

      select: '',
      label: '',
      roles: {},
      rolesList: []
    }
  },

  created() {
    this.getUserInfoList()
  },

  methods: {
    // 获取用户信息列表
    async getUserInfoList() {
      try {
        const res = await getInfoList({
          pagenum: this.CurrentPage,
          pagesize: this.PageSize
        })
        this.tableData.push(...res.data.users)
        this.total = res.data.total
        this.CurrentPage = res.data.pagenum
      } catch (error) {
        console.log(error)
      }
    },

    // handleSizeChange每页条数发生改变时
    async handleSizeChange(val) {
      try {
        const res = await getInfoList({
          query: this.input,
          pagenum: this.CurrentPage,
          pagesize: val
        })
        console.log(res)
        this.tableData = []
        this.tableData.push(...res.data.users)
        this.total = res.data.total
        this.CurrentPage = res.data.pagenum
        this.ChangeSize = val
      } catch (error) {
        console.log(error)
      }
    },

    // currentPage 当前页改变时会触发
    async handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      try {
        const res = await getInfoList({
          query: this.input,
          pagenum: val,
          pagesize: this.ChangeSize || this.PageSize
        })
        console.log(res)
        this.tableData = []
        this.tableData.push(...res.data.users)
        this.total = res.data.total
        this.CurrentPage = res.data.pagenum
      } catch (error) {
        console.log(error)
      }
    },

    // 添加用户信息
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await addUserInfo(this.numberValidateForm)
          this.dialogFormVisible = false
          this.$message({
            message: '恭喜你，添加用户成功',
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 改变用户状态
    async ChangeState(e) {
      // console.log(e)
      try {
        await PutUserState(e.id, e.mg_state)
        this.$message({
          message: '恭喜你，更新用户状态成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 修改用户 弹层
    PutUser(e) {
      console.log(e)
      this.EditDialog = true
      this.EditUser = e
      this.EditDialogForm.username = e.username
      this.EditDialogForm.email = e.email
      this.EditDialogForm.mobile = e.mobile
    },

    // 提交修改用户
    async submitEdit() {
      try {
        const res = await EditUserInfo(
          this.EditUser.id,
          this.EditDialogForm.email,
          this.EditDialogForm.mobile
        )
        this.$message({
          message: '恭喜你，更新用户信息成功',
          type: 'success'
        })
        console.log(res)
        this.tableData = []
        this.getUserInfoList()
        this.EditDialog = false
      } catch (error) {
        console.log(error)
      }
    },

    // 删除用户
    DelUser(e) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await DeleteUser(e.id)
          this.tableData = []
          this.getUserInfoList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 分配角色
    RolesUser(e) {
      this.RolesDialog = true
      console.log(e)
      this.roles = e
    },
    async onselect() {
      const res = await RolesList()
      console.log(res)
      this.rolesList = res.data
    },
    // 提交分配角色
    async onRoleSave() {
      try {
        await putUserRole(this.roles.id, this.select)
        this.RolesDialog = false
        this.$message({
          type: 'success',
          message: '分配成功了哦!'
        })
      } catch (error) {
        console.log(error)
      }
    },

    async selectUser() {
      console.log(this.input)
      this.tableData = []
      const res = await getInfoList({
        query: this.input,
        pagenum: this.CurrentPage,
        pagesize: this.PageSize
      })
      console.log(res)
      this.tableData = res.data.users
      this.total = res.data.total
      this.CurrentPage = res.data.pagenum
    }
  }
}
</script>

<style scoped lang="scss">
.Users {
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .card_body {
    background-color: #fff;
    margin: 10px;
    .form {
      padding: 20px 20px 10px 20px;
      .Search_input {
        margin-right: 10px;
        .el-input {
          width: 500px;
        }
        .el-button--primary {
          margin-left: 20px !important;
        }
      }

      .el-table {
        margin: 15px 0;
        button {
          width: 44px;
          height: 28px;
        }
      }
    }
    .el-pagination {
      padding: 0 0 20px 20px !important;
    }
  }
  .roles-box {
    div {
      padding: 10px;
    }
    span {
      padding: 10px 0 10px 10px;
    }
  }
}
</style>
